// pages/modify_person_info/modify_person_info.js
// import Toast from '@vant/weapp/toast/toast';
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userName:'',
    userPhone:'',
    imgUrl: '',
    choosed: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.setData({
      userName: app.globalData.userName,
      userPhone: app.globalData.userPhone,
      imgUrl: app.globalData.imgUrl,
      choosed: false
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      userName: app.globalData.userName,
      userPhone: app.globalData.userPhone,
      imgUrl: app.globalData.imgUrl
    })
  },

  /**
   * 睡眠等待函数
   */
  delay(milSec) {
    return new Promise(resolve => {
      setTimeout(resolve, milSec)
    })
  },

  onChooseAvatar(e){
    var imgUrl = e.detail.avatarUrl
    this.setData({
      imgUrl: imgUrl,
      choosed: true
    })
  },

  async onSubmit(e) {
    if (e.detail.value.userPhone.length != 11) {
      wx.showToast({ // 显示Toast
        title: '手机号有误',
        icon: 'error',
        duration: 1500
      })

      return
    }

    var that = this
    this.setData({
      userName: e.detail.value.userName,
      userPhone: e.detail.value.userPhone
    })
    if (this.data.choosed) {
      await wx.cloud.uploadFile({
        cloudPath: 'userPhoto/' + Date.now() + '.jpg', // 上传至云端的路径
        filePath: that.data.imgUrl, // 小程序临时文件路径
      }).then(res => {
        that.setData({imgUrl: res.fileID})
      })
      app.setUserInfo(this.data.userName, this.data.userPhone, this.data.imgUrl)
    }
    await wx.cloud.database().collection('user_info').doc(app.globalData.docId).update({
      // data 传入需要局部更新的数据
      data: {
        userName: e.detail.value.userName,
        userPhone: e.detail.value.userPhone,
        imgUrl: that.data.imgUrl
      }
    })
    // 操作反馈
    await wx.showToast({ // 显示Toast
      title: '修改成功',
      icon: 'success',
      duration: 1500
    })

    await this.delay(1000)
    wx.switchTab({
      url: '../me/me',
    })
  }
})